package com.hup.minicontroller.client.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.hup.minicontroller.client.ClientApplication;
import com.hup.minicontroller.client.R;
import com.hup.minicontroller.client.model.AppState;
import com.hup.minicontroller.client.service.MainService;
import com.hup.minicontroller.common.constant.NetConstant;
import com.hup.minicontroller.common.constant.NetConstant.ConnectType;
import com.hup.minicontroller.common.model.dto.ControlConfigDto;
import com.hup.minicontroller.common.view.AnimationAdapter;
import com.hup.minicontroller.common.view.SeekBarView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainForm {
    private static final String TAG = MainForm.class.getSimpleName();
    public static final int RESOURCE_ID = R.layout.activity_main;

    //投屏图像
    @BindView(R.id.screenView)
    public ScreenView screenView;
    //连接面板
    @BindView(R.id.txtAppName)
    public TextView txtAppName;
    @BindView(R.id.layoutConnect)
    public ConstraintLayout layoutConnect;
    @BindView(R.id.txtToConnect)
    public EditText txtToConnect;
    @BindView(R.id.btnConnectLan)
    public Button btnConnectLan;
    //
    @BindView(R.id.layoutHotspot)
    public View layoutHotspot;
    @BindView(R.id.txtHotspotGateway)
    public TextView txtHotspotGateway;
    @BindView(R.id.btnConnectHotspot)
    public Button btnConnectHotspot;
    //扫描到的服务端
    @BindView(R.id.lvScannedServer)
    public ListView lvScannedServer;

    //已连接面板
    @BindView(R.id.layoutConnected)
    public LinearLayout layoutConnected;
    @BindView(R.id.txtServerInfo)
    public TextView txtServerInfo;
    @BindView(R.id.txtNetSpeed)
    public TextView txtNetSpeed;
    //配置面板
    @BindView(R.id.cbEnableScreen)
    public Switch cbEnableScreen;
    @BindView(R.id.sbFps)
    public SeekBarView<Integer> sbFps;
    @BindView(R.id.sbScreenSize)
    public SeekBarView<Integer> sbScreenSize;
    @BindView(R.id.sbScreenQuality)
    public SeekBarView<Integer> sbScreenQuality;
    @BindView(R.id.btnDrawFull)
    public Switch btnDrawFull;
    @BindView(R.id.btnShowFunctionButton)
    public Switch btnShowFunctionButton;
    //功能按钮
    @BindView(R.id.btnBack)
    public ImageView btnBack;
    @BindView(R.id.btnHome)
    public ImageView btnHome;
    @BindView(R.id.btnApp)
    public ImageView btnApp;
    @BindView(R.id.btnDisconnect)
    public Button btnDisconnect;
    /**
     * 禁控模式的标签
     */
    @BindView(R.id.txtDisableControl)
    public TextView txtDisableControl;
    @BindView(R.id.layoutHideConnectedPanel)
    public View layoutHideConnectedPanel;
    @BindView(R.id.touchPadView)
    public TouchPadView touchPadView;
    @BindView(R.id.buttonFloater)
    public ButtonFloaterView buttonFloater;

    private final AppState appState;
    private final Animation animPanelShow, animPanelHide;

    @SuppressLint("ClickableViewAccessibility")
    public MainForm(Activity activity) {
        ButterKnife.bind(this, activity);
        this.appState = ClientApplication.getBean(MainService.class).getAppState();
        animPanelShow = AnimationUtils.loadAnimation(activity, R.anim.main_panel_show);
        animPanelHide = AnimationUtils.loadAnimation(activity, R.anim.main_panel_hide);
        animPanelHide.setAnimationListener(new AnimationAdapter() {
            @Override
            public void onAnimationEnd(Animation animation) {
                layoutConnected.setVisibility(View.GONE);
            }
        });

        sbFps.setValues(parse(NetConstant.FPS));
        sbScreenSize.setValues(parse(NetConstant.SCREEN_SIZE));
        sbScreenQuality.setValues(parse(NetConstant.SCREEN_QUALITY));

        initListener();
    }

    /**
     * 添加仅和ui相关的监听
     */
    private void initListener() {
        btnDrawFull.setOnCheckedChangeListener((v, isChecked) -> {
            appState.getAppConfig().setDrawFull(isChecked);
            screenView.setFull(isChecked);
        });
        btnShowFunctionButton.setOnCheckedChangeListener((v, isChecked) -> {
            appState.getAppConfig().setShowFunctionButton(isChecked);
            buttonFloater.switchFunctionButton(isChecked);
        });
        layoutHideConnectedPanel.setOnClickListener(v -> {
            layoutHideConnectedPanel.setVisibility(View.GONE);
            layoutConnected.startAnimation(animPanelHide);
        });
        buttonFloater.btnTrigger.setOnClickListener(v -> {
            boolean show = layoutConnected.getVisibility() != View.VISIBLE;
            layoutHideConnectedPanel.setVisibility(show ? View.VISIBLE : View.GONE);
            if (show) layoutConnected.setVisibility(View.VISIBLE);
            layoutConnected.startAnimation(show ? animPanelShow : animPanelHide);
        });
        buttonFloater.setDraggedCallback(() -> {
            View parent = (View) buttonFloater.getParent();
            float xPercent = buttonFloater.getX() / parent.getWidth();
            float yPercent = buttonFloater.getY() / parent.getHeight();
            Log.i(TAG, "setButtonFloaterLocation: " + xPercent + "," + yPercent);
            appState.getAppConfig().setButtonFloaterLocation(xPercent, yPercent);
        });
    }

    private String parse(int[] array) {
        StringBuilder sb = new StringBuilder();
        for (int val : array) {
            sb.append(val).append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public void onConnectionChanged() {
        boolean connected = appState.getConnectedType() != null;
        Log.i(TAG, "onConnectionChanged: " + connected);
        updateViewByModel(connected);
    }

    public void updateViewByModel(boolean connected) {
        //代码顺序遵循布局文件中的顺序
        if (!connected) {//未连接
            screenView.switchVisible(false);
            layoutConnect.setVisibility(View.VISIBLE);
            layoutConnected.setVisibility(View.GONE);
            txtDisableControl.setVisibility(View.GONE);
            layoutHideConnectedPanel.setVisibility(View.GONE);
            touchPadView.setVisibility(View.GONE);
            buttonFloater.setVisibility(View.GONE);
            return;
        }
        //已连接
        layoutConnect.setVisibility(View.GONE);
        String lanServerHost = appState.getConnectedType() == ConnectType.LAN ? ", " + appState.getLanServerHost() : "";
        txtServerInfo.setText(String.format("已连接:%s, %s%s", appState.getServerName(), appState.getConnectedType().desc, lanServerHost));
        btnDisconnect.setEnabled(true);
        updateControlComponents(appState.getControlConfig());
    }

    public void updateControlComponents(ControlConfigDto controlConfig) {
        screenView.switchVisible(controlConfig.isEnableScreen());
        if (!controlConfig.isEnableScreen() && layoutConnected.getVisibility() == View.GONE) {
            layoutConnected.setVisibility(View.VISIBLE);
            layoutConnected.startAnimation(animPanelShow);
        }
        //图像配置
        cbEnableScreen.setChecked(controlConfig.isEnableScreen());
        sbFps.setVisibility(controlConfig.isEnableScreen() ? View.VISIBLE : View.GONE);
        sbScreenSize.setVisibility(controlConfig.isEnableScreen() ? View.VISIBLE : View.GONE);
        sbScreenQuality.setVisibility(controlConfig.isEnableScreen() ? View.VISIBLE : View.GONE);
        btnDrawFull.setVisibility(controlConfig.isEnableScreen() ? View.VISIBLE : View.GONE);
        if (controlConfig.isEnableScreen()) {
            sbFps.setValue(controlConfig.getFps());
            sbScreenSize.setValue(controlConfig.getScreenSize());
            sbScreenQuality.setValue(controlConfig.getScreenQuality());
            btnDrawFull.setChecked(appState.getAppConfig().isDrawFull());
        }
        boolean isTouchPad = controlConfig.isEnableControl() && !controlConfig.isEnableScreen();
        btnShowFunctionButton.setVisibility(controlConfig.isEnableControl() && !isTouchPad ? View.VISIBLE : View.GONE);
        if (controlConfig.isEnableControl())
            btnShowFunctionButton.setChecked(appState.getAppConfig().isShowFunctionButton());
        //功能控制
        btnBack.setVisibility(controlConfig.isEnableControl() ? View.VISIBLE : View.GONE);
        btnHome.setVisibility(controlConfig.isEnableControl() ? View.VISIBLE : View.GONE);
        btnApp.setVisibility(controlConfig.isEnableControl() ? View.VISIBLE : View.GONE);
        //禁控模式
        txtDisableControl.setVisibility(!controlConfig.isEnableControl() ? View.VISIBLE : View.GONE);
        layoutHideConnectedPanel.setVisibility(layoutConnected.getVisibility());
        //触控板模式
        touchPadView.setVisibility(isTouchPad ? View.VISIBLE : View.GONE);
        buttonFloater.setVisibility(!isTouchPad ? View.VISIBLE : View.GONE);
        boolean showFloaterButton = controlConfig.isEnableControl() && appState.getAppConfig().isShowFunctionButton();
        buttonFloater.switchFunctionButton(showFloaterButton);
    }

}